const moment = require('moment')
const axios = require('axios')


//获取市场情绪

//@Bean
class MarketSentimentService {

	//@Autowired
	lifeCircleService;

	//@Autowired
	systemLogService;

	//@Value(invest.buy_sentiment_max)
	buy_sentiment_max;

	//@Value(invest.sell_sentiment_min)
	sell_sentiment_min;


	//更新数据
	async requsetNewsData(){
		try{
			const {data} = await axios.get('https://api.alternative.me/fng/')
			this.lifeCircleService.updateMarketSentiment(+data.data[0].value);
		}catch(e){
			this.systemLogService.operateError(`获取市场情绪请求错误:${e}`)
		}
	}

	//自动采集采集一次
	async autoUpdate(hour=1){

		await this.requsetNewsData();

		setInterval(async ()=>{

			await this.requsetNewsData();

		},1000*60*60*hour)
	}

	//获取交易策略
	getTxStrategy (coin,price){

		const {buy_sentiment_max,sell_sentiment_min} = this;
		const sentiment = this.lifeCircleService.getSentiment();


		if(sentiment<=buy_sentiment_max){

			const amount = ((50-sentiment)/100+1)*coin.amount;

			const size = Math.max(amount.toFixed(2),coin.min_buy_amount)

			return {type:'buy',size,realAmount:size,unit:"USDT"};
		}

		if(sentiment>=sell_sentiment_min){

			const amount = ((sentiment *1.5)/100+1)*coin.amount;

			//获取最小交易精度
			const fixed = (coin.min_sell_size+"").length-2;

			const preSellAmount = (amount/price).toFixed(fixed);

			const size = Math.max(preSellAmount,coin.min_sell_size)

			return {type:'sell',size,realAmount:amount,unit:coin.name.split("-")[0]};
		}

		return {type:'None',size:0,realAmount:0,unit:''};
	}



}

module.exports = { MarketSentimentService }